import 'package:flutter/material.dart';

/// 匹配到的文字用红色高亮，支持设置高亮样式，常用于搜索结果展示
/// 如果有多处匹配，只会显示最前面的
class HighlightedText extends StatelessWidget {
  final String text;
  final String? highlight;
  final TextStyle? textStyle;
  final TextStyle? highlightStyle;
  final Color? highlightColor;
  final bool ignoreCase;

  const HighlightedText({
    Key? key,
    required this.text,
    this.highlight,
    this.textStyle,
    this.highlightStyle,
    this.highlightColor,
    this.ignoreCase = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final indexOf = highlight == null
        ? -1
        : ignoreCase
            ? text.toLowerCase().indexOf(highlight!.toLowerCase())
            : text.indexOf(highlight!);
    final textStyle = this.textStyle ?? Theme.of(context).textTheme.bodyMedium;
    final highlightStyle = this.highlightStyle ??
        textStyle!.copyWith(
          color: highlightColor ?? Theme.of(context).colorScheme.error,
        );
    return highlight == null || indexOf == -1
        ? Text(
            text,
            style: textStyle,
          )
        : RichText(
            text: TextSpan(
              text: text.substring(0, indexOf),
              style: textStyle,
              children: <TextSpan>[
                TextSpan(
                  text: text.substring(indexOf, indexOf + highlight!.length),
                  style: highlightStyle,
                ),
                TextSpan(
                  text: text.substring(indexOf + highlight!.length),
                  style: textStyle,
                ),
              ],
            ),
          );
  }
}
